package com.example.anju.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.anju.entity.Result;
import com.example.anju.entity.User;
import com.example.anju.mapper.UserMapper;

@Service
public class UserService {
	@Autowired
	private UserMapper userMapper;

	// 注册
	public Result register(User user) {
		Result result = new Result();
		result.setSuccess(false);
		result.setDatas(null);
		try {
			List<User> userByAccount = userMapper.findUserByAccount(user.getAccount());// 查询是否已经存在
			if (!userByAccount.isEmpty()) {// 如果查询到，表示用户已存在
				result.setMessage("用户已存在");
			} else {
				userMapper.register(user);// 如果未查询到，表示用户不存在，则注册用户
				result.setMessage("注册成功");
				result.setSuccess(true);
				userByAccount = userMapper.findUserByAccount(user.getAccount());// 查询是否已经存在
				result.setDatas(userByAccount);
			}
		} catch (Exception e) {
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return result;
	}

	// 登录
	public Result login(User user) {
		Result result = new Result();
		result.setSuccess(false);
		result.setDatas(null);
		try {
			Integer user_id = userMapper.login(user);// 登录，返回user_id的结果
			if (user_id == null) {// 若user_id为空，表示用户不存在
				result.setMessage("用户名或密码错误");
			} else {// 若user_id不为空，表示用户存在
				result.setMessage("登录成功");
				result.setSuccess(true);
				user.setUser_id(user_id);
				List<User> userById = userMapper.findUserById(user_id);
				result.setDatas(userById);
			}

		} catch (Exception e) {
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return result;
	}
}
